package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.DTO.LotteryChancesVO;
import com.ruoyi.common.core.domain.DTO.PurchaseRecordVO;
import com.ruoyi.common.core.domain.DTO.SignInVO;
import com.ruoyi.common.core.domain.DTO.UpdateUserPointsAndLogBO;
import com.ruoyi.common.core.domain.entity.SignInRecord;
import com.ruoyi.common.core.domain.entity.SignInStatistics;
import com.ruoyi.system.mapper.SignInMapper;
import com.ruoyi.system.mapper.SignInStatisticsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Transactional
public class SigninService {
    @Autowired
    private SignInMapper signInMapper;
    @Autowired
    private PrizeService prizeService;
    @Autowired
    private SignInStatisticsMapper signInStatisticsMapper;
    @Autowired
    private PointsService pointsService;
    @Autowired
    private InviteRecordService inviteRecordService;
    @Autowired
    private PurchaseRecordService purchaseRecordService;

    public void signIn(Long userId) {
        //签到积分
//        Integer signInPoints = 1;
        Integer totalDays = 1;
        Integer continuousDays = 1;
        Integer totalContinuousDays = 1;
        //查询用户上一次打卡记录
        SignInRecord record = signInMapper.selectPreviousByUserId(userId);
        if (!ObjectUtils.isEmpty(record)) {
            totalDays = record.getTotalDays() + 1;
            if (isOneDayDifference(record.getSignDate(), new Date())) {
                continuousDays = record.getContinuousDays() + 1;
                totalContinuousDays = record.getTotalContinuousDays() + 1;
            }
        }
        // 签到
        SignInRecord signInRecord = new SignInRecord();
        signInRecord.setUserId(userId);
        Date date = new Date();
        signInRecord.setSignDate(date);
        signInRecord.setSignTime(date);
        signInRecord.setStatus(1);
        signInRecord.setContinuousDays(continuousDays);
        signInRecord.setTotalContinuousDays(totalContinuousDays);
        signInRecord.setTotalDays(totalDays);
        signInRecord.setCreatedAt(date);
        signInRecord.setUpdatedAt(date);
        signInMapper.insertSignInRecord(signInRecord);
        // 更新用户积分
        /*UpdateUserPointsAndLogBO updateUserPointsAndLogBO = new UpdateUserPointsAndLogBO();
        updateUserPointsAndLogBO.setUserId(userId);
        updateUserPointsAndLogBO.setPoints(signInPoints);
        updateUserPointsAndLogBO.setPointsType(2);
        updateUserPointsAndLogBO.setSource("签到");
        updateUserPointsAndLogBO.setRelatedOrderNo(signInRecord.getId().toString());
        prizeService.updateUserPointsAndLog(updateUserPointsAndLogBO);*/
        //更新用户签到统计
        updateSignInStatistics(userId,continuousDays);
    }

    public void updateSignInStatistics(Long userId, Integer continuousDays) {
        SignInStatistics signInStatistics = signInStatisticsMapper.selectByUserId(userId);
        if (ObjectUtils.isEmpty(signInStatistics)) {
            signInStatistics = new SignInStatistics();
            signInStatistics.setUserId(userId);
            signInStatistics.setWeeksCount(1);
            signInStatistics.setCreatedAt(new Date());
            signInStatistics.setUpdatedAt(new Date());
            signInStatisticsMapper.insertSignInStatistics(signInStatistics);
        } else {
            int weeksCount = signInStatistics.getWeeksCount() + 1;
            signInStatistics.setWeeksCount(weeksCount);
            boolean isContinuous = continuousDays % 3 == 0;
            if (weeksCount == 5 || isContinuous) {
                signInStatistics.setLevelOneCount(signInStatistics.getLevelOneCount() + 1);
            }
            signInStatistics.setUpdatedAt(new Date());
            signInStatisticsMapper.updateSignInStatisticsById(signInStatistics);
        }
    }

    //查询签到记录列表
    public SignInVO selectSignInRecordList(Long userId) {
        SignInVO signInVO = new SignInVO();
        List<SignInRecord> records = signInMapper.selectSignInRecordList(userId);
        if (ObjectUtils.isEmpty(records)) {
            return signInVO;
        }
        signInVO.setSignInRecordList(records);
        signInVO.setTotalDays(records.size());
        signInVO.setContinuousDays(records.get(0).getContinuousDays());
        return signInVO;
    }

    //根据签到日期和用户id查询用户签到记录
    public SignInRecord selectSignInRecordBySignDateAndUserId(String signDate, Long userId) {
        return signInMapper.selectSignInRecordBySignDateAndUserId(signDate, userId);
    }

    public boolean isOneDayDifference(Date date1, Date date2) {
        long diffInMillies = Math.abs(date1.getTime() - date2.getTime());
        long diffInDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
        return diffInDays == 1;
    }

    //重置一级抽奖次数
    public void updateWeeksCount() {
        //更新用户签到统计表
        SignInStatistics signInStatistics = new SignInStatistics();
        signInStatistics.setWeeksCount(0);
        signInStatistics.setLevelOneCount(0);
        signInStatistics.setUpdatedAt(new Date());
        signInStatisticsMapper.updateSignInStatistics(signInStatistics);
        //更新用户签到记录表
        SignInRecord signInRecord = new SignInRecord();
        signInRecord.setContinuousDays(0);
        signInRecord.setUpdatedAt(new Date());
        signInMapper.updateSignInRecord(signInRecord);
    }

    //根据用户id更新二级抽奖次数
    public void updateLevelTwoCount() {
        List<Long> eligibleUserIds = selectEligibleUserIds();
        signInStatisticsMapper.updateLevelTwoCount(eligibleUserIds);
    }

    //根据用户id更新三级抽奖次数
    public void updateLevelThreeCount() {
        List<Long> eligibleUserIds = selectEligibleUserIds();
        signInStatisticsMapper.updateLevelThreeCount(eligibleUserIds);
    }

    //获取会员用户且推广两人的用户ids
    public List<Long> selectEligibleUserIds() {
        List<Long> eligibleUserIds = new ArrayList<>();
        List<Long> userIds = pointsService.selectLevelTwoUserId();
        if (!ObjectUtils.isEmpty(userIds)) {
            userIds.forEach(userId -> {
                //获取直属下级人员id
                List<Long> directUserIds = inviteRecordService.selectDirectTeamUserIds(userId);
                //获取购买过产品的用户id
                List<Long> purchaseUserIds = selectPurchaseUserIds(directUserIds);
                if (!ObjectUtils.isEmpty(purchaseUserIds) && purchaseUserIds.size() >= 2) {
                    eligibleUserIds.add(userId);
                }
            });
        }
        return eligibleUserIds;
    }

    //查询购买过产品的用户id
    public List<Long> selectPurchaseUserIds(List<Long> userIds) {
        List<Long> purchaseUserIds = new ArrayList<>();
        userIds.forEach(userId -> {
            Integer payCounts = purchaseRecordService.selectPayCountByUserId(userId);
            if (!ObjectUtils.isEmpty(payCounts)&& payCounts >= 1) {
                purchaseUserIds.add(userId);
            }
        });
        return purchaseUserIds;
    }

    //根据用户id查询签到统计
    public LotteryChancesVO selectSignInStatisticsByUserId(Long userId) {
        SignInStatistics signInStatistics = signInStatisticsMapper.selectByUserId(userId);
        LotteryChancesVO lotteryChancesVO = new LotteryChancesVO();
        if (ObjectUtils.isEmpty(signInStatistics)) {
            return lotteryChancesVO;
        }
        lotteryChancesVO.setLevelOneCount(signInStatistics.getLevelOneCount());
        lotteryChancesVO.setLevelTwoCount(signInStatistics.getLevelTwoCount());
        lotteryChancesVO.setLevelThreeCount(signInStatistics.getLevelThreeCount());
        return lotteryChancesVO;
    }
}
